package com.hmall.cart.listener;

import com.hmall.api.client.CartClient;
import com.hmall.cart.service.ICartService;
import com.hmall.common.constants.MqConstants;
import com.hmall.common.utils.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class OrderStatusListener {

    private final ICartService cartService;
//    private final CartClient cartService;
    //接收来自 cart.clear.queue 队列的消息;清理用户对于的购物车商品
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "cart.clear.queue", durable = "true"),
            exchange = @Exchange(value = MqConstants.TRADE_EXCHANGE_NAME, type = ExchangeTypes.TOPIC,  durable = "true"),
            key = MqConstants.ROUTING_KEY_ORDER_CREATE
    ))
    public void listenOrderCreate(List<Long> itemIds, @Header("user-info")Long userId) {
        log.error("开始处理订单创建成功消息");
        //设置用户id消息到线程池
        UserContext.setUser(userId);
        log.error("接收到订单创建成功消息,itemIds:{},userId:{}", itemIds, userId);
        //清理用户对应的购物车商品
        cartService.removeByItemIds(itemIds);
        //释放锁--删除Usercontext中用户信息
        UserContext.removeUser();
    }
}
